package com.phpxiu.app.view.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.phpxiu.app.api.OnDialogClickListener;
import com.phpxiu.app.api.listener.OnUserManageWinListener;
import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.CurLiveInfo;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.MsgSender;
import com.phpxiu.app.model.card.RoomCard;
import com.phpxiu.app.model.card.RoomCardInfo;
import com.phpxiu.app.model.event.OnChatRoomReply;
import com.phpxiu.app.model.event.OnRefreshFollowCount;
import com.phpxiu.app.model.response.AdminModel;
import com.phpxiu.app.model.response.MuteModel;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.OKHttpResponseModel;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.C2CChat;
import com.phpxiu.app.view.RoomManagers;
import com.phpxiu.app.view.UserHome;
import com.phpxiu.app.view.custom.FrescoImageView;

import de.greenrobot.event.EventBus;

/**
 * Created by WuJinZhou on 2016/5/26.
 */
public class RoomUserCard extends Dialog implements View.OnClickListener,OnUserManageWinListener,OnDialogClickListener {
    public final static String TAG="RoomUserCard";
    private TextView manageBtn;
    private FrescoImageView mAvatar;
    private TextView nickTv;
    private ImageView sexIconView;
    private FrescoImageView lvIconView;
    private TextView idView;
    private TextView introTv;
    private TextView attentionNum,fansNum,costValue,dotValue;
    private View bottomBar;
    private Button msgBtn,attentionBtn,replyBtn,goHomeBtn;
    private boolean isAdmin=false;//true以管理员身份查看卡片
    private boolean isAdminCard=false;//被查看的用户是否为管理员角色
    private String uid;
    private String nick;
    private String avatar;
    private RoomManageMenus manageMenus;
    private OKHttpParam reportParam,shutParam;
    private InteractiveDialog reportDlg;
    private Alert reportTip;
    private boolean isAttention=false;
    private OKHttpParam attentionParam;
    private boolean canOpenMenus=true;//false如果通过操作菜单提交的请求未响应，不能再次打开操作菜单
    private LiveRoomWin parent;

    private String blockState;//黑状态标记

    private String reportTitle,manageTitle,ticketsLabel,costLabel,followTitle,unFollowTitle,fansLabel,chatTitle,replyTitle,homeTitle;
    public RoomUserCard(Context context) {
        super(context, R.style.shareBoardDialog);
        init(context);
    }

    /**
     * 初始化窗口
     */
    private void init(Context context){
        setContentView(R.layout.main_room_user_card_win);
        initString(context);
        findViewById(R.id.main_room_user_card_win).setOnClickListener(this);
        manageBtn=(TextView)findViewById(R.id.main_room_card_win_manage_user_btn);
        manageBtn.setOnClickListener(this);
        findViewById(R.id.main_room_card_win_close_btn).setOnClickListener(this);
        mAvatar=(FrescoImageView)findViewById(R.id.main_room_card_win_head_view);
        nickTv=(TextView)findViewById(R.id.main_room_card_user_nick);
        sexIconView=(ImageView)findViewById(R.id.user_sex_icon_view);
        lvIconView=(FrescoImageView)findViewById(R.id.user_lvl_icon_view);
        idView=(TextView)findViewById(R.id.main_room_card_user_id_view);
        introTv=(TextView)findViewById(R.id.main_room_card_user_intro);
        attentionNum=(TextView)findViewById(R.id.user_attention_num);
        fansNum=(TextView)findViewById(R.id.user_fans_num);
        dotValue=(TextView)findViewById(R.id.user_dot_value);
        costValue=(TextView)findViewById(R.id.user_cost_value);
        bottomBar=findViewById(R.id.main_room_user_card_bottom_bar);
        msgBtn=(Button)findViewById(R.id.user_msg_btn);
        msgBtn.setOnClickListener(this);
        attentionBtn=(Button)findViewById(R.id.user_attention_btn);
        attentionBtn.setOnClickListener(this);
        replyBtn=(Button)findViewById(R.id.user_reply_msg);
        replyBtn.setOnClickListener(this);
        goHomeBtn=(Button)findViewById(R.id.go_user_home_btn);
        goHomeBtn.setOnClickListener(this);

    }

    private void initString(Context context){
        reportTitle=context.getString(R.string.ui_room_menus_report);
        manageTitle=context.getString(R.string.ui_room_menus_manage);
        ticketsLabel=context.getString(R.string.ui_room_card_tickets_label);
        costLabel=context.getString(R.string.ui_room_card_cost_label);
        followTitle=context.getString(R.string.ui_room_card_follow_label);
        unFollowTitle=context.getString(R.string.ui_room_card_followed_title);
        fansLabel=context.getString(R.string.ui_room_card_fans_label);
        chatTitle=context.getString(R.string.ui_room_card_msg_title);
        replyTitle=context.getString(R.string.ui_room_card_reply_title);
        homeTitle=context.getString(R.string.ui_room_card_home_title);
    }

    /**
     * 刷新内容
     */
    private void refreshWindow(RoomCard content){
        RoomCardInfo info=content.getInfo();
        boolean isSelf=MySelfInfo.getInstance().getId().equals(info.getUid());
        uid=info.getUid();
        nick=info.getNickname();
        avatar=info.getAvatar();
        blockState=content.getMyinfo().getBlock();
        boolean isBlock="1".equals(blockState);
        String ship=content.getMyinfo().getRelationship();
        String admin=content.getMyinfo().getIsadmin();
        if("1".equals(ship)||"2".equals(ship)){
            isAttention=true;
        }else{
            isAttention=false;
        }
        if(!isSelf) {
            manageBtn.setVisibility(View.VISIBLE);
            isAdmin = false;
            manageBtn.setText(reportTitle);
            if(MySelfInfo.getInstance().getIdStatus()== Constants.HOST){
                isAdminCard="1".equals(info.getIsadmin());
                if(isAdminCard){
                    KKYUtil.log("被查看者是管理员");
                }
                manageBtn.setText(manageTitle);
            }else{
                if(admin!=null&&!"".equals(admin)){
                    if("1".equals(admin)){
                        isAdmin = true;
                        manageBtn.setText(manageTitle);
                    }
                }
            }
        }else{
            manageBtn.setVisibility(View.INVISIBLE);
        }
        mAvatar.setImageURI(Uri.parse(info.getAvatar()));
        nickTv.setText(nick);
        if("1".equals(info.getSex())){
            sexIconView.setImageResource(R.mipmap.user_sex_icon_male);
        }else{
            sexIconView.setImageResource(R.mipmap.user_sex_icon_female);
        }
        if(!"".equals(info.getLvl())){
            lvIconView.setImageURI(Uri.parse("asset:///lvIcons/" + info.getLvl() + ".png"));
        }
        idView.setText("ID:"+info.getUid());
        introTv.setText(info.getIntro());

        dotValue.setText(info.getTotal_income());
        costValue.setText(info.getSpend());
        attentionNum.setText(info.getFollownum());
        fansNum.setText(info.getFansnum());
        if(isSelf){
            bottomBar.setVisibility(View.GONE);
        }else{//显示部份操作按钮
            if(bottomBar.getVisibility()!=View.VISIBLE){
                bottomBar.setVisibility(View.VISIBLE);
            }
            if(isAttention){
                attentionBtn.setText(unFollowTitle);
            }else{
                attentionBtn.setText(followTitle);
            }
        }
    }

    public void setParent(LiveRoomWin parent) {
        this.parent = parent;
    }

    public void show(RoomCard content) {
        refreshWindow(content);
        super.show();
    }

    /**
     * 私信
     * @param uid
     */
    public void onMsg(String uid) {
        Intent chat=new Intent(getContext(),C2CChat.class);
        chat.putExtra(C2CChat.EXTRA_CONVERSATION_ID,uid);
        chat.putExtra(C2CChat.EXTRA_USER_ID,uid);
        chat.putExtra(C2CChat.EXTRA_USER_NICK_NAME,nick);
        chat.putExtra(C2CChat.EXTRA_USER_AVATAR,avatar);
        chat.putExtra(C2CChat.EXTRA_BLOCK_SING,blockState);
        getContext().startActivity(chat);
    }

    /**
     * 举报
     */
    private void report(){
        if(reportDlg==null){
            reportDlg=new InteractiveDialog(getContext());
            reportDlg.setTitle(getContext().getString(R.string.ui_room_report_title));
            reportDlg.setSummary(getContext().getString(R.string.ui_room_report_content));
            reportDlg.setOkTitle(getContext().getString(R.string.ui_room_menus_report));
            reportDlg.setCancelTitle(getContext().getString(R.string.list_menus_cancel));
            reportDlg.setOnDialogClickListener(this);
        }
        reportDlg.show();
    }

    /**
     * 确定举报
     */
    @Override
    public void onOk() {
        submitReport();
    }
    /**
     * 取消举报
     */
    @Override
    public void onCancel() {

    }

    /**
     * 提交举报
     */
    private void submitReport(){
        if(uid==null||"".equals(uid)){
            return;
        }
        if(reportParam==null){
            reportParam=OKHttpParam.builder();
        }
        reportParam.put("tid",uid);
        OKHttp.post(HttpConfig.API_REPORT_USER, reportParam.jsonParam(), TAG, new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                if(reportTip==null){
                    reportTip=new Alert(getContext());
                    reportTip.setMsg(getContext().getString(R.string.room_report_success));
                    reportTip.setOnClickListener(null);
                }
                reportTip.show();
            }

            @Override
            public void onErr(String errMsg) {
                KKYUtil.log("举报失败：" + errMsg);
            }
        });
    }


    /**
     * 显示管理选项
     */
    private void showManageOptions(){
        if(manageMenus==null){
            manageMenus=new RoomManageMenus(getContext());
            manageMenus.getWindow().getAttributes().width=(int) KKYApp.getInstance().screenWidth;
            manageMenus.addOnUserManageListener(this);
        }
        manageMenus.show(isAdminCard);
    }

    /**
     * 关注操作
     */
    private void attentionOpera(){
        KKYUtil.log(TAG, "当前关注状态：" + isAttention);
        if(attentionParam==null){
            attentionParam=OKHttpParam.builder();
        }
        attentionParam.put("uid",uid);
        String url=null;
        if(isAttention){
            url=HttpConfig.API_CANCEL_ATTENTION_USER;
        }else {
            url=HttpConfig.API_ATTENTION_USER;
        }
        attentionBtn.setEnabled(false);
        OKHttp.post(url, attentionParam.jsonParam(), TAG, new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                KKYUtil.log("关注状态操作成功!");
                attentionBtn.setEnabled(true);
                if (isAttention) {
                    EventBus.getDefault().post(new OnRefreshFollowCount(false));//更新我的关注数量
                    attentionBtn.setText(followTitle);
                } else {
                    EventBus.getDefault().post(new OnRefreshFollowCount(true));//更新我的关注数量
                    if (CurLiveInfo.getHostID().equals(uid)) {//如果是主播
                        if (parent != null) {
                            parent.broadcastAttention();//广播关注消息
                        }
                    }
                    attentionBtn.setText(unFollowTitle);
                }
                isAttention = !isAttention;
            }
            @Override
            public void onErr(String errMsg) {
                attentionBtn.setEnabled(true);
            }
        });
    }

    /**
     *回复某人
     */
    private void replySomeBody(){
        dismiss();
        EventBus.getDefault().post(new OnChatRoomReply(uid, nick));
    }

    /**
     * 用户主页
     */
    private void userHome(){
        Intent home=new Intent(getContext(), UserHome.class);
        home.putExtra(UserHome.EXTRA_PARAM_KEY_UID,uid);
        getContext().startActivity(home);
        dismiss();
    }


    /**
     * 重置内容
     */
    private void reset(){
        isAdmin=false;
        isAdminCard=false;
        manageBtn.setText(reportTitle);
        uid=null;
        mAvatar.setImageURI(Uri.parse("res:///"+R.drawable.def_user_icon));
        nickTv.setText("");
        lvIconView.setImageURI(Uri.parse("asset:///lvIcons/1.png"));
        idView.setText("ID:--");
        introTv.setText("");
        attentionNum.setText("0");
        fansNum.setText("0");
        costValue.setText("0");
        dotValue.setText("0");
    }

    @Override
    public void onReport() {
        manageMenus.dismiss();
        report();
    }

    @Override
    public void onAdminOpera() {
        OKHttpParam param=OKHttpParam.builder();
        param.put("uid",uid);
        String url=null;
        if(isAdminCard){
           url=HttpConfig.API_CANCEL_ADMIN;
        }else{
            url=HttpConfig.API_SET_ADMIN;
        }
        canOpenMenus=false;
        OKHttp.post(url, param.jsonParam(), TAG, new OKHttpUIHandler(AdminModel.class) {
            @Override
            public void onSuccess(Object model) {
                AdminModel m = (AdminModel) model;
                KKYUtil.log("管理操作结果" + m.getResponseStr());
                if (isAdminCard) {
                    KKYUtil.log("取消管理成功");
                } else {
                    KKYUtil.log("设置管理成功");
                }
                if (parent != null) {
                    parent.broadcastAdmin(m.getData().getTuser(), isAdminCard);
                }
                isAdminCard = !isAdminCard;
                canOpenMenus = true;
            }

            @Override
            public void onErr(String errMsg) {
                canOpenMenus = true;
                KKYUtil.log("管理更改失败：" + errMsg);
            }
        });
    }

    @Override
    public void adminList() {
        if(MySelfInfo.getInstance().getIdStatus()==Constants.HOST) {
            Intent manager = new Intent(getContext(), RoomManagers.class);
            manager.putExtra(RoomManagers.EXTRA_PARAM_ROOM_ID,CurLiveInfo.getHostID());
            getContext().startActivity(manager);
        }
    }

    @Override
    public void onSpeakOpera() {
        if(true){//直接广播禁言通知
            MsgSender muter=new MsgSender();
            muter.setUid(uid);
            muter.setNickname(nick);
            if(parent!=null){
                parent.broadcastMute(muter);
            }
            return;
        }
        if(shutParam==null){
            shutParam=OKHttpParam.builder();
        }
        shutParam.put("uid",uid);
        shutParam.put("host_id", CurLiveInfo.getHostID());
        OKHttp.post(HttpConfig.API_MUTE_USER,shutParam.jsonParam(),TAG,new OKHttpUIHandler(MuteModel.class) {
            @Override
            public void onSuccess(Object model) {
                MuteModel m=(MuteModel)model;
                if(parent!=null){
                    parent.broadcastMute(m.getData().getTuser());
                }
            }

            @Override
            public void onErr(String errMsg) {
                KKYUtil.log("禁言失败...");
            }
        });
        manageMenus.dismiss();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.main_room_card_win_manage_user_btn:
                if(uid==null||"".equals(uid)){
                    return;
                }
                if(MySelfInfo.getInstance().getIdStatus()==Constants.HOST||isAdmin){
                    if(canOpenMenus) {
                        showManageOptions();
                    }
                }else{
                    report();
                }
                break;
            case R.id.user_msg_btn:
                onMsg(uid);
                break;
            case R.id.user_attention_btn:
                attentionOpera();
                break;
            case R.id.user_reply_msg:
                replySomeBody();
                break;
            case R.id.go_user_home_btn:
                userHome();
                break;
            case R.id.main_room_user_card_win:
            case R.id.main_room_card_win_close_btn:
                dismiss();
                break;
            default:
                break;
        }
    }

    @Override
    public void dismiss() {
        parent=null;
        reset();
        super.dismiss();
    }

}
